// 实时数据监控模块 - 演示高级Vuex特性
export default {
    namespaced: true,
    
    state: {
        // 实时指标数据
        metrics: {
            cpu: 0,           // CPU使用率
            memory: 0,        // 内存使用率
            network: 0,       // 网络流量
            activeUsers: 0,   // 活跃用户数
            requests: 0       // 请求数量
        },
        
        // 历史数据记录
        history: [],
        
        // 数据过滤条件
        filters: {
            dateRange: 'today',
            metricType: 'all',
            minValue: 0,
            maxValue: 100
        },
        
        // 数据订阅状态
        subscriptions: [],
        
        // 最后更新时间
        lastUpdate: null,
        
        // 数据流状态
        isStreaming: false,
        
        // WebSocket连接状态
        connectionStatus: 'disconnected', // 'connected', 'connecting', 'disconnected', 'error'
        
        // 错误信息
        errors: [],
        
        // 导出状态
        exportStatus: null
    },
    
    mutations: {
        // 更新实时指标
        UPDATE_METRICS(state, metrics) {
            state.metrics = { ...state.metrics, ...metrics }
            state.lastUpdate = new Date()
        },
        
        // 添加历史记录
        SAVE_HISTORY(state, record) {
            state.history.push({
                timestamp: new Date(),
                data: { ...state.metrics },
                ...record
            })
            
            // 保持历史记录在合理范围内（最多保存1000条）
            if (state.history.length > 1000) {
                state.history = state.history.slice(-1000)
            }
        },
        
        // 设置过滤条件
        SET_FILTERS(state, filters) {
            state.filters = { ...state.filters, ...filters }
        },
        
        // 添加订阅
        ADD_SUBSCRIPTION(state, subscription) {
            state.subscriptions.push({
                id: Date.now(),
                type: subscription.type,
                interval: subscription.interval,
                callback: subscription.callback,
                active: true,
                createdAt: new Date()
            })
        },
        
        // 移除订阅
        REMOVE_SUBSCRIPTION(state, id) {
            const index = state.subscriptions.findIndex(sub => sub.id === id)
            if (index > -1) {
                state.subscriptions.splice(index, 1)
            }
        },
        
        // 设置数据流状态
        SET_STREAMING_STATUS(state, status) {
            state.isStreaming = status
        },
        
        // 设置连接状态
        SET_CONNECTION_STATUS(state, status) {
            state.connectionStatus = status
        },
        
        // 添加错误信息
        ADD_ERROR(state, error) {
            state.errors.push({
                id: Date.now(),
                message: error.message,
                type: error.type || 'error',
                timestamp: new Date()
            })
            
            // 保持错误记录在合理范围内
            if (state.errors.length > 50) {
                state.errors = state.errors.slice(-50)
            }
        },
        
        // 清除错误
        CLEAR_ERRORS(state) {
            state.errors = []
        },
        
        // 设置导出状态
        SET_EXPORT_STATUS(state, status) {
            state.exportStatus = status
        },
        
        // 清空历史数据
        CLEAR_HISTORY(state) {
            state.history = []
        }
    },
    
    actions: {
        // 开始实时数据流
        async startDataStream({ commit, dispatch, state }) {
            if (state.isStreaming) {
                return { success: false, message: '数据流已经在运行中' }
            }
            
            commit('SET_STREAMING_STATUS', true)
            commit('SET_CONNECTION_STATUS', 'connecting')
            
            try {
                // 模拟WebSocket连接
                await new Promise(resolve => setTimeout(resolve, 1000))
                commit('SET_CONNECTION_STATUS', 'connected')
                
                // 开始定时生成模拟数据
                const generateData = () => {
                    if (state.isStreaming) {
                        const metrics = {
                            cpu: Math.floor(Math.random() * 100),
                            memory: Math.floor(Math.random() * 100),
                            network: Math.floor(Math.random() * 1000),
                            activeUsers: Math.floor(Math.random() * 500) + 100,
                            requests: Math.floor(Math.random() * 10000) + 1000
                        }
                        
                        commit('UPDATE_METRICS', metrics)
                        
                        // 每10秒保存一次历史记录
                        if (state.history.length === 0 || 
                            Date.now() - new Date(state.history[state.history.length - 1].timestamp).getTime() > 10000) {
                            commit('SAVE_HISTORY')
                        }
                        
                        setTimeout(generateData, 2000) // 每2秒更新一次
                    }
                }
                
                generateData()
                return { success: true, message: '数据流启动成功' }
                
            } catch (error) {
                commit('SET_CONNECTION_STATUS', 'error')
                commit('ADD_ERROR', { message: error.message, type: 'connection' })
                commit('SET_STREAMING_STATUS', false)
                return { success: false, message: '数据流启动失败' }
            }
        },
        
        // 停止实时数据流
        stopDataStream({ commit }) {
            commit('SET_STREAMING_STATUS', false)
            commit('SET_CONNECTION_STATUS', 'disconnected')
            return { success: true, message: '数据流已停止' }
        },
        
        // 获取历史数据
        async fetchHistoryData({ commit }, { startDate, endDate }) {
            try {
                // 模拟API请求
                await new Promise(resolve => setTimeout(resolve, 1500))
                
                // 生成模拟历史数据
                const historyData = []
                const start = new Date(startDate)
                const end = new Date(endDate)
                const interval = (end - start) / 50 // 生成50个数据点
                
                for (let i = 0; i < 50; i++) {
                    const timestamp = new Date(start.getTime() + i * interval)
                    historyData.push({
                        timestamp,
                        data: {
                            cpu: Math.floor(Math.random() * 100),
                            memory: Math.floor(Math.random() * 100),
                            network: Math.floor(Math.random() * 1000),
                            activeUsers: Math.floor(Math.random() * 500) + 100,
                            requests: Math.floor(Math.random() * 10000) + 1000
                        }
                    })
                }
                
                // 替换历史数据
                historyData.forEach(record => {
                    commit('SAVE_HISTORY', record)
                })
                
                return { success: true, data: historyData }
                
            } catch (error) {
                commit('ADD_ERROR', { message: error.message, type: 'fetch' })
                return { success: false, message: '获取历史数据失败' }
            }
        },
        
        // 应用数据过滤
        applyFilters({ commit }, filters) {
            commit('SET_FILTERS', filters)
            return { success: true }
        },
        
        // 导出数据
        async exportData({ state, commit }, format = 'json') {
            commit('SET_EXPORT_STATUS', 'pending')
            
            try {
                // 模拟导出处理
                await new Promise(resolve => setTimeout(resolve, 2000))
                
                const exportData = {
                    metrics: state.metrics,
                    history: state.history,
                    exportTime: new Date(),
                    format
                }
                
                // 模拟下载
                const dataStr = format === 'json' 
                    ? JSON.stringify(exportData, null, 2)
                    : exportData.history.map(h => 
                        `${h.timestamp},${h.data.cpu},${h.data.memory},${h.data.network},${h.data.activeUsers},${h.data.requests}`
                      ).join('\n')
                
                commit('SET_EXPORT_STATUS', 'success')
                
                // 在实际应用中，这里会触发文件下载
                console.log('Exported data:', dataStr)
                
                return { success: true, data: dataStr }
                
            } catch (error) {
                commit('SET_EXPORT_STATUS', 'failed')
                commit('ADD_ERROR', { message: error.message, type: 'export' })
                return { success: false, message: '导出失败' }
            }
        },
        
        // 添加数据订阅
        addSubscription({ commit }, subscription) {
            commit('ADD_SUBSCRIPTION', subscription)
            return { success: true }
        },
        
        // 清除错误
        clearErrors({ commit }) {
            commit('CLEAR_ERRORS')
        }
    },
    
    getters: {
        // 过滤后的历史数据
        filteredHistory: (state) => {
            let filtered = [...state.history]
            
            // 按日期范围过滤
            if (state.filters.dateRange === 'today') {
                const today = new Date()
                today.setHours(0, 0, 0, 0)
                filtered = filtered.filter(record => 
                    new Date(record.timestamp) >= today
                )
            } else if (state.filters.dateRange === 'week') {
                const weekAgo = new Date()
                weekAgo.setDate(weekAgo.getDate() - 7)
                filtered = filtered.filter(record => 
                    new Date(record.timestamp) >= weekAgo
                )
            }
            
            // 按指标类型过滤
            if (state.filters.metricType !== 'all') {
                filtered = filtered.filter(record => {
                    const value = record.data[state.filters.metricType]
                    return value >= state.filters.minValue && value <= state.filters.maxValue
                })
            }
            
            return filtered
        },
        
        // 实时状态汇总
        systemStatus: (state) => {
            const { cpu, memory, network, activeUsers, requests } = state.metrics
            
            return {
                overall: cpu < 80 && memory < 80 ? 'healthy' : 'warning',
                details: {
                    cpu: cpu < 80 ? 'normal' : 'high',
                    memory: memory < 80 ? 'normal' : 'high',
                    network: network < 800 ? 'normal' : 'high'
                },
                lastUpdate: state.lastUpdate
            }
        },
        
        // 活跃订阅数量
        activeSubscriptionCount: (state) => {
            return state.subscriptions.filter(sub => sub.active).length
        },
        
        // 连接状态描述
        connectionInfo: (state) => {
            const statusMap = {
                connected: { text: '已连接', color: 'success' },
                connecting: { text: '连接中', color: 'warning' },
                disconnected: { text: '已断开', color: 'info' },
                error: { text: '连接错误', color: 'error' }
            }
            
            return statusMap[state.connectionStatus] || statusMap.disconnected
        },
        
        // 数据统计
        dataStats: (state, getters) => {
            const history = getters.filteredHistory
            
            if (history.length === 0) {
                return null
            }
            
            const calculateStats = (key) => {
                const values = history.map(h => h.data[key])
                return {
                    min: Math.min(...values),
                    max: Math.max(...values),
                    avg: Math.round(values.reduce((a, b) => a + b, 0) / values.length),
                    latest: state.metrics[key]
                }
            }
            
            return {
                cpu: calculateStats('cpu'),
                memory: calculateStats('memory'),
                network: calculateStats('network'),
                activeUsers: calculateStats('activeUsers'),
                requests: calculateStats('requests')
            }
        },
        
        // 错误统计
        errorSummary: (state) => {
            const errors = state.errors
            const recentErrors = errors.filter(error => 
                Date.now() - new Date(error.timestamp).getTime() < 3600000 // 最近1小时
            )
            
            return {
                total: errors.length,
                recent: recentErrors.length,
                byType: errors.reduce((acc, error) => {
                    acc[error.type] = (acc[error.type] || 0) + 1
                    return acc
                }, {})
            }
        }
    }
}